/*
 * This file is part of Sponge, licensed under the MIT License (MIT).
 *
 * Copyright (c) SpongePowered <https://www.spongepowered.org>
 * Copyright (c) contributors
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.spongepowered.mod;

import com.google.common.collect.ImmutableMap;
import net.minecraftforge.fml.common.MetadataCollection;
import net.minecraftforge.fml.common.ModMetadata;
import org.spongepowered.common.SpongeImpl;
import org.spongepowered.plugin.meta.McModInfo;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;

import javax.annotation.Nullable;

public final class SpongeModMetadata {

    @Nullable
    private static MetadataCollection metadata;

    private SpongeModMetadata() {
    }

    public static void load() {
        if (metadata != null) {
            return;
        }

        try {
            String source = SpongeCoremod.modFile.toURI().toString();
            boolean isJar = source.endsWith(".jar");

            Enumeration<URL> urls = SpongeModMetadata.class.getClassLoader().getResources(McModInfo.STANDARD_FILENAME);
            while (urls.hasMoreElements()) {
                URL url = urls.nextElement();

                if (isJar) {
                    if (!"jar".equals(url.getProtocol())) {
                        continue;
                    }

                    if (!url.getPath().startsWith(source)) {
                        // mcmod.info from different mod
                        continue;
                    }
                } else if (!"file".equals(url.getProtocol())) {
                    continue;
                }

                // Attempt to parse file
                try (InputStream in = url.openStream()) {
                    metadata = MetadataCollection.from(in, url.toString());
                    ModMetadata meta = getSpongeForgeMetadata();

                    if (!meta.autogenerated) {
                        SpongeImpl.getLogger().info("Found mcmod.info at {}", url);
                        return;
                    }

                    // Continue searching (in development environment we may have the wrong mcmod.info file)
                }
            }
        } catch (IOException e) {
            SpongeImpl.getLogger().warn("Failed to load metadata", e);
        }

        if (metadata == null) {
            metadata = new MetadataCollection();
        }
    }

    public static ModMetadata get(String modId, String name) {
        load();
        ModMetadata meta = metadata.getMetadataForId(modId, ImmutableMap.of(
                "name", name,
                "version", ""
        ));

        if (!meta.autogenerated) {
            if (meta.name == null) {
                meta.name = name;
            }

            if (meta.version == null) {
                meta.version = "";
            }
        }

        return meta;
    }

    public static ModMetadata getSpongeForgeMetadata() {
        return get(SpongeImpl.ECOSYSTEM_ID, "SpongeForge");
    }

}
